package com.qire.manhua.model.viewModel.impl;

import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;

import com.qire.antsrouter.AntsRouter;
import com.qire.common.basic.DateUtil;
import com.qire.common.constant.CacheStorageKey;
import com.qire.common.constant.Navigation;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.DialogManage;
import com.qire.common.utils.CacheStorageUtil;
import com.qire.common.utils.ToastHelper;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.dialog.AutoPayTipsDialog;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.entity.ComicBookEntity.LockInfo;
import com.qire.manhua.model.entity.ComicBookEntity.DiscountInfo;
import com.qire.manhua.model.entity.ComicBookEntity.DirectoryInfo;
import com.qire.manhua.model.enumeration.FreeType;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;

/**
 * 章节解锁浮层ViewModel
 */
public class UnlockChapterDialogViewModel extends BaseObservable {

    private int           comicBookId;
    private LockInfo      lockInfo;
    private DiscountInfo  discountInfo;
    private DirectoryInfo directoryInfo;

    //由于需要保留上次支付记录，固使用静态字段。boolean非实体对象固不用担心OOM，且Dialog只可能同时存在一个固不会出现脏数据。
    private static boolean isBeanUnlockPanel;

    private boolean needHintVipFree      = false;
    private boolean needHintVipPrivilege = false;
    private boolean canAdUnlock          = false;
    private boolean needTipsAutoSwitch   = false;

    public UnlockChapterDialogViewModel() {
        this.isBeanUnlockPanel = CacheStorageUtil.queryBoolean(CacheStorageKey.LAST_UNLOCK_IS_BEAN);
    }

    public DirectoryInfo getDirectoryInfo() {
        return directoryInfo;
    }

    public int getChapterId() {
        return directoryInfo.chapterId;
    }

    public String getBuyPriceStr() {
        return lockInfo.buyPriceStr;
    }

    /**
     * 判断用户账户余额是否足够解锁本章，如果选择金币解锁，则只判定金币是否足够，否则判定金豆，不在做混合累计
     * @return 余额不足够支付时true,否则false
     * */
    public boolean isInsufficientBalanceByPanel() {
        float unLockBalance = isBeanUnlockPanel ? UserEntity.self.getBeanBalance() : UserEntity.self.getCoinBalance();
        return unLockBalance < lockInfo.buyPrice;
    }

    /**
     * 判断用户账户余额是否足够解锁本章节
     * @return 金币或金豆存在一种足够解锁都返回false,否则返回true
     */
    public boolean isInsufficientBalance() {
        if(UserEntity.self.getBeanBalance() >= lockInfo.buyPrice)
            return false;
        if(UserEntity.self.getCoinBalance() >= lockInfo.buyPrice)
            return false;
        return true;
    }

    /**
     * @return 漫画ID
     */
    public int comicBookId() {
        return comicBookId;
    }

    //region    #属性设置 begin
    public void loadComicData(ComicBookEntity comicBookEntity, DirectoryInfo directoryInfo) {
        this.comicBookId    = comicBookEntity.id;
        this.lockInfo       = comicBookEntity.lockInfo();
        this.discountInfo   = comicBookEntity.discountInfo();
        this.directoryInfo  = directoryInfo;

        refresh();
    }

    public void refresh() {
        if(directoryInfo == null) {
            return;
        }

        FreeType bookFreeType = lockInfo.bookFreeType;
        boolean isBookFree = bookFreeType == FreeType.VipFree ? true : false;

        if(bookFreeType == FreeType.VipLimitTimeFree) {
            boolean isValid = DateUtil.yMdHms.assertToTodayValid(lockInfo.limitFreeTime + ":59", 0, false);
            if(isValid) {
                isBookFree = true;
            }
        }

        /***************************************************************************************************
         * 1.如果选择了7日不在显示，则不显示VIP优惠引导面板，noLongerRemind为true不显示
         * 2.如果会员特权面板现实过则不在显示会员特权面板。privilegeShown为true不显示
         ***************************************************************************************************/
        long noLongerRemindTime = CacheStorageUtil.queryLong(CacheStorageKey.NO_LONGER_REMIND_LAST_TIME);
        boolean noLongerRemind = DateUtil.yMdHms.assertToTodayValid(noLongerRemindTime, 7);
        boolean privilegeShown = CacheStorageUtil.queryBoolean(CacheStorageKey.PRIVILEGE_SHOWN);

        needHintVipFree      = isBookFree && (!UserEntity.self.isVip() && directoryInfo.isVipFree) && !noLongerRemind;
        needHintVipPrivilege = directoryInfo.haveLock() && !needHintVipFree && !privilegeShown;
        canAdUnlock          = directoryInfo.canUnlockedByAd() && UserEntity.self.canAdUnlocked();

        if (needHintVipPrivilege) {
            CacheStorageUtil.save(CacheStorageKey.PRIVILEGE_SHOWN, true);
        }

        notifyChange();
    }

    public void noLongerRemind() {
        CacheStorageUtil.save(CacheStorageKey.NO_LONGER_REMIND_LAST_TIME, System.currentTimeMillis());
    }

    public boolean isBeanUnlockPanel() {
        return isBeanUnlockPanel;
    }

    /**
     * 设置余额解锁时是否需要提示余额不足自动切换了解锁方式。如金豆切换金币。
     */
    public void tipsAutoSwitch() {
        needTipsAutoSwitch = true;
    }

    public void toggleUnlockPanel() {
        needHintVipFree      = false;
        needHintVipPrivilege = false;
        canAdUnlock          = false;
        refreshPanel();
    }

    public void toggleUnlockPanelTabs() {
        isBeanUnlockPanel = !isBeanUnlockPanel;
        CacheStorageUtil.save(CacheStorageKey.LAST_UNLOCK_IS_BEAN, isBeanUnlockPanel);
        notifyPropertyChanged(BR.toggleBtnBgRid);
        notifyPropertyChanged(BR.buyChapterCoinPrompt);
        notifyPropertyChanged(BR.descriptionInfo);
        notifyPropertyChanged(BR.paymentBtnText);
        notifyPropertyChanged(BR.balancePrompt);
    }
    //endregion #属性设置 end

    //region    #面板控制显示 begin
    private void refreshPanel() {
        notifyPropertyChanged(BR.loginPanelVisible);
        notifyPropertyChanged(BR.copyrightPanelVisible);
        notifyPropertyChanged(BR.vipFreePanelVisible);
        notifyPropertyChanged(BR.vipPrivilegePanelVisible);
        notifyPropertyChanged(BR.adUnlockPanelVisible);
        notifyPropertyChanged(BR.unLockPanelVisible);
    }

    @Bindable
    public CharSequence getTitle() {
        return directoryInfo.chapterName;
    }
    
    //未登录提示面板
    @Bindable
    public int getLoginPanelVisible() {
        return UserEntity.self.isLogin() ? View.GONE : View.VISIBLE;
    }
    //版权到期提示面板
    @Bindable
    public int getCopyrightPanelVisible() {
        if(!UserEntity.self.isLogin())
            return View.GONE;
        return lockInfo.isCopyrightExpired() ? View.VISIBLE : View.GONE;
    }
    //会员免费提示面板
    @Bindable
    public int getVipFreePanelVisible() {
        if(!UserEntity.self.isLogin())
            return View.GONE;
        if(lockInfo.isCopyrightExpired())
            return View.GONE;
        if(needHintVipFree&&!canAdUnlock)
            return View.VISIBLE;
        return View.GONE;
    }
    //会员特权提示面板
    @Bindable
    public int getVipPrivilegePanelVisible() {
        if(!UserEntity.self.isLogin())
            return View.GONE;
        if(lockInfo.isCopyrightExpired())
            return View.GONE;
        if(canAdUnlock)
            return View.GONE;
        if(needHintVipPrivilege)
            return View.VISIBLE;
        return View.GONE;
    }
    //广告解锁面板
    @Bindable
    public int getAdUnlockPanelVisible() {
        if(!UserEntity.self.isLogin())
            return View.GONE;
        if(lockInfo.isCopyrightExpired())
            return View.GONE;
        if(canAdUnlock)
            return View.VISIBLE;
        return View.GONE;
    }
    //余额解锁面板
    @Bindable
    public int getUnLockPanelVisible() {
        //未登录
        if(!UserEntity.self.isLogin())
            return View.GONE;
        //版权到期
        if(lockInfo.isCopyrightExpired())
            return View.GONE;
        //可以广告解锁
        if(canAdUnlock)
            return View.GONE;
        //需要提示会员免费
        if(needHintVipFree)
            return View.GONE;
        //需要提示会员特权
        if(needHintVipPrivilege)
            return View.GONE;

        // 如果是从余额不足自动切换过来的，需要提示
        if (needTipsAutoSwitch) {
            needTipsAutoSwitch = false;
            String msg = isBeanUnlockPanel() ? "金币不足，已切换为金豆解锁" : "金豆不足，已切换为金币解锁";
            ToastHelper.showToast(msg);
        }

        //如果唤起解锁弹窗说明一定是需要解锁的章节，所以默认解锁显示。
        return View.VISIBLE;
    }
    //endregion #面板控制显示 end

    //region    #会员解锁面板属性绑定 begin
    @Bindable
    public CharSequence getIntroduction() {
        return lockInfo.lockIntroduction;//会员免费阅读此本漫画
    }

    @Bindable
    public CharSequence getLimitFreeTime() {
        if(lockInfo.limitFreeTime != null)
            return buildLimitFreeTime();
        if(!UserEntity.self.isVip())
            return buildVipDiscountInfo();
        return buildVipExpiration();
    }

    private CharSequence buildLimitFreeTime() {
        if(lockInfo.limitFreeTime == null) {
            return "";
        }
        Date date = DateUtil.yMdHms.parse(lockInfo.limitFreeTime);
        if(date == null) {
            return "";
        }
//        int validDays = - DateUtil.yyyy_MM_dd_HHmmss.calcDaysDifferenceToToday(date);
//        SpannableStringBuilder builder = new SpannableStringBuilder("会员限免剩余时间：" + validDays + "天");
        String validDaysTips = DateUtil.yMdHms.toSomeday(date).formatBy(TimeUnit.MILLISECONDS::toDays, "会员限免剩余时间：", "天");
        SpannableStringBuilder builder = new SpannableStringBuilder(validDaysTips);
        ForegroundColorSpan fgSpan = new ForegroundColorSpan(Color.rgb(0xff, 0x54, 0x20));
        builder.setSpan(fgSpan, 0, builder.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return builder;
    }

    private CharSequence buildVipDiscountInfo() {
        if(discountInfo == null) {
            return "";
        }

        SpannableStringBuilder builder = new SpannableStringBuilder("当前共");

        int startIndex = builder.length();
        builder.append(String.valueOf(discountInfo.notFreeCount));
        ForegroundColorSpan fgSpan1 = new ForegroundColorSpan(Color.rgb(0xff, 0x54, 0x20));
        builder.setSpan(fgSpan1, startIndex, builder.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        builder.append("个付费章节，可节省");
        startIndex = builder.length();
        builder.append(String.valueOf(discountInfo.discountAmount));
        ForegroundColorSpan fgSpan2 = new ForegroundColorSpan(Color.rgb(0xff, 0x54, 0x20));
        builder.setSpan(fgSpan2, startIndex, builder.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        builder.append("元");
        return builder;
    }
    private CharSequence buildVipExpiration() {
        if(!UserEntity.self.isVip()) {
            return "";
        }
        return "有效期至：" + UserEntity.self.getVipExpirationTime();
    }

    //endregion #会员解锁面板属性绑定 end

    //region    #会员特权面板属性绑定 begin
    @Bindable
    public CharSequence getVipIntroduction() {
        int start, end;
        SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append("本章为付费章节，需金币或金豆解锁\n开通会员立享");
        start = builder.length();
        builder.append("7折");
        end = builder.length();
        builder.append("优惠");

        ForegroundColorSpan prefixFgSpan = new ForegroundColorSpan(Color.rgb(0xff, 0x54, 0x20));
        builder.setSpan(prefixFgSpan, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

        return builder;
    }
    //endregion #会员特权面板属性绑定 end

    //region    #广告解锁面板属性绑定 begin
    @Bindable
    public CharSequence getAdUnlockCountTips() {
        return String.format("今日剩%d次", UserEntity.self.getCanAdUnlockedCount());
    }

    @Bindable
    public int getBuyMembershipBtnVisible() {
        return needHintVipFree ? View.VISIBLE : View.GONE;
    }

    @Bindable
    public int getToggleUnlockPanelBtnVisible() {
        return needHintVipFree ? View.GONE : View.VISIBLE;
    }
    //endregion #广告解锁面板属性绑定 end

    //region    #购买解锁面板属性绑定 begin
    @Bindable
    public int getToggleBtnBgRid() {
        return isBeanUnlockPanel ? R.drawable.app_comic_reader_unlock_panel_b : R.drawable.app_comic_reader_unlock_panel_a;
    }

    @Bindable
    public CharSequence getBuyChapterCoinPrompt() {
        SpannableStringBuilder builder = new SpannableStringBuilder("本章需支付");

        ForegroundColorSpan prefixFgSpan = new ForegroundColorSpan(Color.rgb(0x33, 0x33, 0x33));
        builder.setSpan(prefixFgSpan, 0, builder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

        int startIndex = builder.length();
        builder.append(String.valueOf(lockInfo.buyPrice));
        if(isBeanUnlockPanel) {
            builder.append("金豆");
        } else {
            builder.append("金币");
        }

        ForegroundColorSpan fgSpan = new ForegroundColorSpan(Color.rgb(0xff, 0x54, 0x20));
        builder.setSpan(fgSpan, startIndex, builder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        return builder;
    }

    @Bindable
    public CharSequence getDescriptionInfo() {
        if(!UserEntity.self.isLogin()) {
            return "";
        }
        if(isBeanUnlockPanel && isInsufficientBalanceByPanel()) {
            return buildBeanTaskDescription();
        }
        return buildVipDiscountDescription();
    }

    private SpannableStringBuilder buildBeanTaskDescription() {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append("做任务可免费获得金豆，");
        int startIndex = builder.length();
        builder.append("去做任务");
        ForegroundColorSpan fgSpan = new ForegroundColorSpan(Color.rgb(0x48, 0x8a, 0xe5));
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                AntsRouter.ROUTER.buildCard(Navigation.Page.TaskCenterPage).navigation();
                DialogManage.lastDialog().dismiss();
            }
            @Override
            public void updateDrawState( TextPaint ds) {}
        };
        builder.setSpan(clickableSpan, startIndex, builder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        builder.setSpan(fgSpan, startIndex, builder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        return builder;
    }

    private SpannableStringBuilder buildVipDiscountDescription() {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        if (UserEntity.self.isVip()){

            int discount = 70;//固定七折，没有85折了

            builder.append("原价");
            builder.append(String.valueOf(lockInfo.originalPrice));

            if(isBeanUnlockPanel) {
                builder.append("金豆，");
            } else {
                builder.append("金币，");
            }

            builder.append("正在享受会员");
            int startIndex = builder.length();
            builder.append(new BigDecimal(discount).divide(new BigDecimal(10)).toString()+"折");
            int endIndex   = builder.length();
            builder.append("优惠");
            ForegroundColorSpan fgSpan = new ForegroundColorSpan(Color.rgb(0xff, 0x54, 0x20));
            builder.setSpan(fgSpan, startIndex, endIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        } else {
            builder.append("会员解锁只需").append(lockInfo.vipPriceStr);

            if(isBeanUnlockPanel) {
                builder.append("金豆，");
            } else {
                builder.append("金币，");
            }

            int startIndex = builder.length();
            builder.append("开通会员");
            ForegroundColorSpan fgSpan = new ForegroundColorSpan(Color.rgb(0x48, 0x8a, 0xe5));
            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    AntsRouter.ROUTER.buildCard(Navigation.Page.BuyMembershipDialogPage).navigation();
                    DialogManage.lastDialog().dismiss();
                }
                @Override
                public void updateDrawState( TextPaint ds) {}
            };
            builder.setSpan(clickableSpan, startIndex, builder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            builder.setSpan(fgSpan, startIndex, builder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        }
        return builder;
    }

    @Bindable
    public MovementMethod getDescriptionInfoMovementMethod() {
        return LinkMovementMethod.getInstance();
    }

    @Bindable
    public String getPaymentBtnText() {
        return isInsufficientBalanceByPanel() ? "余额不足，请立即充值" : "解锁本章";
    }

    @Bindable
    public String getBalancePrompt() {
        if(isBeanUnlockPanel) {
            return "账户余额：" + UserEntity.self.getBeanBalance() + "金豆";
        } else {
            return "账户余额：" + UserEntity.self.getCoinBalance() + "金币";
        }
    }

    @Bindable
    public String getAutoUnlockTextColor() {
//        return UserEntity.self.isAutoPay() ? "#19a554" : "#909090";
        return "#909090";
    }

    @Bindable
    public boolean getIsAutoUnlock() {
        return UserEntity.self.isAutoPay();
    }
    public void setIsAutoUnlock(boolean isAutoUnlock) {
        UserEntity.self.setAutoPay(isAutoUnlock);
        notifyPropertyChanged(BR.isAutoUnlock);
        notifyPropertyChanged(BR.autoUnlockTextColor);

        if(isAutoUnlock) {
            AutoPayTipsDialog.build().show();
        }
    }
    //endregion #购买解锁面板属性绑定 end

    @Bindable
    public CharSequence getBalanceTips() {
        return isInsufficientBalance() ? "余额不足" : "余额充足";
    }
    @Bindable
    public int getBalanceTipsBgRid() {
        return isInsufficientBalance() ? R.drawable.app_comic_reader_unlock_text_tips_buoy_red : R.drawable.app_comic_reader_unlock_text_tips_buoy_green;
    }
}
